const app = getApp();
Page({
  data: {
    userInfo: {},
    fromid: '',
    attachurl: app.siteInfo.attachment_url,
    score: 0,
    content: '',
    activeColor: 'var(--color-sub-theme)',
    isloading: true,
  },
  onLoad: function(options) {
    let that = this;
    let opts = options || {};
    let wxInfo = wx.getStorageSync('userInfo') || undefined;
    that.loadDefault(options.pid);
    that.setData({
      opts,
      fromid: options.pid,
      themData: app.setThemeColor() || false,
      userInfo: wxInfo || false,
    });
  },
  loadDefault: function(id) {
    let that = this;
    app.util.request({
      url: 'entry/wxapp/api',
      data: {
        type: 2,
        default: 1,
        id,
      },
      module: 'cm_micro_single_page',
      cachetime: '0',
      success(res) {
        that.setData({
          defaultInfo: res.data.data,
          isloading: false,
        });
      },
    });
  },
  // 提交评价
  submit: function() {
    let that = this;
    let content = that.data.content;
    if (!that.data.userInfo) {
      wx.showModal({
        title: '提示',
        content: '请检查网络状态~',
      });
      return false;
    }
    if (content.length === 0 || content.replace(/\s+/g, '').length === 0) {
      wx.showModal({
        title: '提示',
        content: '评论内容不能为空',
      });
    } else {
      // 提交到服务端
      let param = {
        nickname: that.data.userInfo.nickName || '',
        headimgurl: that.data.userInfo.avatarUrl || '',
        openid: that.data.userInfo.openid || '',
        pid: that.data.fromid || '',
        content: that.data.content || '',
        score: that.data.score || '',
        type: 4,
      };
      app.util.request({
        url: 'entry/wxapp/api',
        data: param,
        module: 'cm_micro_single_page',
        cachetime: '0',
        method: 'POST',
        success(res) {
          if (res.data.data === 1) {
            wx.showToast({
              title: '评价成功^_^',
              icon: 'success',
              duration: 500,
            });
            setTimeout(function() {
              wx.redirectTo({
                url: '../comment/comment?pid=' + that.data.fromid,
              });
            }, 1000);
          }
        },
        fail() {
          wx.showToast({
            title: '添加评价失败！',
          });
        },
      });
    }
  },
  handlerRate(e) {
    const {
      readonly = false, score = 0,
    } = e.target.dataset;
    if (readonly) {
      return;
    }
    if (score) {
      this.setData({
        value: score,
        score,
      });
    }
  },
  inputChange: function(e) {
    let that = this;
    that.setData({
      content: e.detail.value,
    });
  },
});